package persistence

import (
	"context"

	"baseService/internal/domain/entities"
	"baseService/internal/domain/repositories"

	"gorm.io/gorm"
)

type userRepository struct {
	repositories.BaseRepository[entities.User]
	repositories.Paginator[entities.User]
	db *gorm.DB
}

// NewUserRepository 创建用户仓储实例
func NewUserRepository(db *gorm.DB) repositories.UserRepository {
	baseRepo := NewBaseRepository[entities.User](db)
	paginator, ok := baseRepo.(repositories.Paginator[entities.User])
	if !ok {
		panic("base repository does not implement paginator")
	}

	return &userRepository{
		BaseRepository: baseRepo,
		Paginator:      paginator,
		db:             db,
	}
}

func (r *userRepository) GetByUsername(ctx context.Context, username string) (*entities.User, error) {
	var user entities.User
	if err := r.db.WithContext(ctx).Where("username = ?", username).First(&user).Error; err != nil {
		return nil, err
	}
	return &user, nil
}

func (r *userRepository) List(ctx context.Context, options *repositories.QueryOptions) ([]*entities.User, int64, error) {
	if options == nil {
		options = &repositories.QueryOptions{}
	}
	options.Normalize(1, 50, 500)
	return r.GetWithPagination(ctx, options.Page, options.PageSize, options)
}
